import React, { Component } from "react";
import { View, Alert, Platform } from "react-native";
import { ListItem, Button } from "react-native-elements";
import CustomHeader from "../../components/CustomHeader";
import AsyncStorage from "@react-native-community/async-storage";
import {
  request,
  getUserName,
  getUserInfo,
  getRandomFileName,
  getFileExtension,
  isTryOut
} from "../../utils";
import SyanImagePicker from "react-native-syan-image-picker";
import AliyunOSS from "aliyun-oss-react-native";
import config from "../../utils/config";
import { MyButton } from "../../components/MyButton";

class Settings extends Component {
  constructor(props) {
    super(props);
    this.state = {
      userInfo: getUserInfo(),
      newAvatar: ""
    };
    AliyunOSS.enableDevMode();
    AliyunOSS.initWithServerSTS(
      config.aliyunOssSts,
      "oss-cn-beijing.aliyuncs.com",
      {
        maxRetryCount: 3,
        timeoutIntervalForRequest: 30,
        timeoutIntervalForResource: 24 * 60 * 60
      }
    );
  }
  componentDidMount() {
    this.getUserInfo();
  }
  getUserInfo = () => {
    const { navigation } = this.props;
    request(
      "user/info",
      {},
      data => {
        global.userInfo = data;
        this.setState({ userInfo: data });
      },
      data =>
        Alert.alert(data, "", [
          { text: "确定", onPress: _ => navigation.replace("Login") }
        ])
    );
  };
  selectImage = _ => {
    if (isTryOut("设置头像", this.props.navigation)) {
      return;
    }
    SyanImagePicker.showImagePicker(
      {
        imageCount: 1,
        isRecordSelected: false,
        showCropCircle: true,
        isCrop: true
      },
      (err, photos) => {
        if (!err) {
          this.uploadAvatar(photos[0]);
        }
      }
    );
  };
  uploadAvatar = image => {
    Alert.alert(JSON.stringify(image));
    let filePath = Platform.OS == "ios" ? image.uri : image.original_uri;
    this.setState({ newAvatar: filePath });
    let newName = getRandomFileName() + "." + getFileExtension(filePath);
    AliyunOSS.asyncUpload("maternal-baby", newName, filePath)
      .then(res => {
        Alert.alert(res);
        console.log(res);
        request("user/updateAvatar", { avatar: newName });
      })
      .catch(error => {
        Alert.alert(error);
        console.log(error);
      });
  };

  render() {
    const { navigation } = this.props;
    const { userInfo, newAvatar } = this.state;
    return (
      <View>
        <CustomHeader title="设置" hideBack />
        <ListItem
          onPress={this.selectImage}
          leftAvatar={{
            source: { uri: newAvatar ? newAvatar : userInfo.Avatar },
            size: "medium"
          }}
          title={getUserName()}
          bottomDivider
        />
        <ListItem
          title="昵称"
          bottomDivider
          rightTitle={userInfo.Name ? userInfo.Name : "设置昵称"}
          rightTitleStyle={{
            width: 200,
            textAlign: "right"
          }}
          rightIcon={{ name: "right", type: "antdesign" }}
          onPress={_ => {
            if (isTryOut("设置昵称", this.props.navigation)) {
              return;
            }
            navigation.navigate("UpdateName", {
              getUserInfo: this.getUserInfo
            });
          }}
        />
        <ListItem
          title="手机"
          bottomDivider
          rightTitle={userInfo.Phone ? userInfo.Phone : "绑定手机"}
          rightTitleStyle={{
            width: 200,
            textAlign: "right"
          }}
          rightIcon={{ name: "right", type: "antdesign" }}
          onPress={_ => {
            if (isTryOut("绑定手机", this.props.navigation)) {
              return;
            }
            navigation.navigate("UpdatePhone", {
              getUserInfo: this.getUserInfo
            });
          }}
        />
        <ListItem
          title="邮箱"
          bottomDivider
          rightTitle={userInfo.Email ? userInfo.Email : "绑定邮箱"}
          rightTitleStyle={{
            width: 200,
            textAlign: "right"
          }}
          rightIcon={{ name: "right", type: "antdesign" }}
          onPress={_ => {
            if (isTryOut("绑定邮箱", this.props.navigation)) {
              return;
            }
            navigation.navigate("UpdateEmail", {
              getUserInfo: this.getUserInfo
            });
          }}
        />
        <ListItem
          title="分享"
          bottomDivider
          rightIcon={{ name: "right", type: "antdesign" }}
          onPress={_ => navigation.navigate("Share")}
        />
        <ListItem
          title="关于"
          bottomDivider
          rightIcon={{ name: "right", type: "antdesign" }}
          onPress={_ => navigation.navigate("About")}
        />
        <ListItem
          title="意见反馈"
          bottomDivider
          rightIcon={{ name: "right", type: "antdesign" }}
          onPress={_ => navigation.navigate("Feedback")}
        />

        <MyButton
          title="退出登录"
          containerStyle={{
            margin: 36
          }}
          onPress={_ => {
            AsyncStorage.setItem("Token", "");
            navigation.replace("Login");
          }}
        />
      </View>
    );
  }
}

export default Settings;
